package com.qf.service.impl;

import com.qf.mapper.CartDao;
import com.qf.service.CartService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
public class CartServiceImpl implements CartService {

    private CartDao cartDao;

    public CartServiceImpl(CartDao cartDao) {
        this.cartDao = cartDao;
    }

    @Override
    public Map<Object, Object> syncCart(Map<Integer, Integer> localCart, Integer userId) {
        //1.本地和服务器都有，以服务器为准
        //2.任何一方没有，就添加到都有
        Map<Object, Object> returnCart = new HashMap<>();
        //处理两个集合的冲突
        List<Map<String, Integer>> goodsMap = cartDao.queryById(userId);
        Map<Object, Object> serverCart = new HashMap<>();
        goodsMap.forEach(x ->{
            serverCart.put(x.get("good_id"),x.get("num"));
        });
        if (localCart.size() == 0) {
            return serverCart;
        }
        Set<Integer> localCartKeys = localCart.keySet();
        for (Object localKey : localCartKeys) {
            //如果包含此商品,则以服务端的为准
            //如果不包含此商品，则以有的一方添加到没有的一方
            if (serverCart.containsKey(localKey)) {
                continue;
            } else if (!serverCart.containsKey(localKey)) {
                //添加到服务端的购物车
                serverCart.put(localKey, localCart.get(localKey));
            }
        }
        //最后同步的结果以服务端的购物车为准
        returnCart = serverCart;
        //更新购物车信息
        cartDao.deleteCartById(userId);
        cartDao.InsertCart(userId, serverCart);
        return returnCart;
    }

    @Override
    public void addGood(Integer userId, Integer goodId) {
        //获取用户购物车所有商品
        List<Map<String, Integer>> goodsMap = cartDao.queryById(userId);
        Map<Integer, Integer> goodMap = new HashMap<>();
        goodsMap.forEach(x ->{
            goodMap.put(x.get("good_id"),x.get("num"));
        });
        //判断加入购物车的商品是否已存在
        if (goodMap.containsKey(goodId.toString())) {
            Integer num = goodMap.get(goodId.toString());
            cartDao.updateOneCart(goodId, userId, num + 1);
        } else {
            cartDao.insertOneCart(goodId, userId, 1);
        }
    }

    @Override
    public void updGood(Integer userId, Integer goodId, Integer num) {
        cartDao.updateOneCart(goodId, userId, num);
    }

    @Override
    public void delGood(Integer userId, Integer goodId) {
        cartDao.deleteOneCart(userId, goodId);
    }
}
